package com.autotest.nore.controller;

import com.autotest.nore.common.exception.LoginVerifyException;
import com.autotest.nore.common.utils.JwtUtils;
import com.autotest.nore.dto.UserDTO;
import com.autotest.nore.request.LoginRequest;
import com.autotest.nore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletRequest;


@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/autotest/login")
    public UserDTO login(@RequestBody LoginRequest request, HttpServletResponse response, HttpServletRequest httpRequest) {
        UserDTO user = userService.getUser(request.getAccount());
        if(user != null) {
          if (user.getPassword().equals(request.getPassword())) {
                response.addHeader("token", JwtUtils.generateToken(user.getUsername()));
                // 将 userName 存储到 Session 中
                HttpSession session = httpRequest.getSession();
                session.setAttribute("userName", user.getUsername());
                user.setPermissions(userService.getUserProjectPermission(user.getId(), user.getLastProject()));
                return user;
            } else {
                throw new LoginVerifyException("账户密码校验失败");
            }
        }else{
            throw new LoginVerifyException("用户不存在");
        }
    }
}
